package com.hfi.security.core.validate.code.impl;

import com.hfi.security.core.validate.code.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author ChangLiang
 * @date 2019/8/14
 */
public abstract class AbstractValidateCodeProcessor<C extends ValidateCode> implements ValidateCodeProcessor {

    @Autowired
    private ValidateCodeRepository validateCodeRepository;

    /**
     * 收集系统中所有的 {@link ValidateCodeGenerator} 接口的实现
     */
    @Autowired
    private Map<String, ValidateCodeGenerator> validateCodeGeneratorMap;

    @Override
    public void create(ServletWebRequest request) throws IOException, ServletRequestBindingException {
        // 生成
        C validateCode = generate(request);
        // 保存到session中
        save(request, validateCode);
        // 发送
        send(request,validateCode);
    }

    private C generate(ServletWebRequest request) {
        String type = getValidateCodeType().toString().toLowerCase();
        String generatorName = type + ValidateCodeGenerator.class.getSimpleName();
        // 依赖查找
        ValidateCodeGenerator codeGenerator = validateCodeGeneratorMap.get(generatorName);
        if (codeGenerator==null) {
            throw new ValidateCodeException("验证码生成器" + generatorName + "不存在");
        }
        return (C) codeGenerator.generate(request);
    }

    private void save(ServletWebRequest request, C validateCode) {
        // 只取验证码和超时事件 防止图片验证码中的图片BufferedImage无法序列化到redis中
        ValidateCode modifiedValidateCode = new ValidateCode(validateCode.getCode(),validateCode.getExpireTime());
        validateCodeRepository.save(request,modifiedValidateCode,getValidateCodeType());
    }

    protected abstract void send(ServletWebRequest request, C validateCode) throws IOException, ServletRequestBindingException;

    @Override
    public void validate(ServletWebRequest request) {

        ValidateCodeType validateCodeType = getValidateCodeType();

        C codeInSession = (C)validateCodeRepository.get(request,validateCodeType);
        // 在hfi-signIn.html中 input name
        String codeInRequest;
        try {
            codeInRequest= ServletRequestUtils.getStringParameter(request.getRequest(), validateCodeType.getParamNameOnValidate());
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }
        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }
        if (codeInSession==null) {
            throw new ValidateCodeException("验证码不存在");
        }
        // 当前时间是否在过期时间之后
        if (LocalDateTime.now().isAfter(codeInSession.getExpireTime())) {
            validateCodeRepository.remove(request, validateCodeType);
            throw new ValidateCodeException("验证码已过期");
        }
        if (!StringUtils.equals(codeInSession.getCode(),codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }
        validateCodeRepository.remove(request,validateCodeType);
    }

    /**
     * 获得子类CodeProcessor可以处理的ValidateCode
     * 子类getClass().getSimpleName()值不同
     * @return
     */
    private ValidateCodeType getValidateCodeType() {
        // 两个子类 ImageCodeProcessor SmsCodeProcessor
        String type = StringUtils.substringBefore(getClass().getSimpleName(), "CodeProcessor");
        return ValidateCodeType.valueOf(type.toUpperCase());
    }

}
